package com.chp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chp.common.util.PageResult;
import com.chp.entity.Category;
import com.chp.entity.Product;
import com.chp.mapper.ProductMapper;
import com.chp.service.ICategoryService;
import com.chp.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chp.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chp
 * @since 2025-01-13
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ICategoryService categoryService;
    //  分页查询
    @Override
    public PageResult<Product> findByPage(Integer page, Integer pageSize) {
        //  开始分页
        Page<Product> page1 = this.page(new Page<>(page, pageSize));

        //  封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    //  条件带分页查询
    @Override
    public PageResult<Product> search(Integer page, Integer pageSize, ProductVO vo) {
        //  进行分页带条件查询
        //  封装查询条件
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getProdName()), "prodName", vo.getProdName());
        wrapper.eq(vo.getPrice() != null, "price", vo.getPrice());
        wrapper.eq(vo.getCatId() != null && vo.getCatId() != 0, "catId", vo.getCatId());
        //  开始分页查询
        Page<Product> page1 = this.page(new Page<>(page, pageSize), wrapper);
        //  处理学生所在班级名称
        page1.getRecords().forEach(st -> {
            Category category = categoryService.getById(st.getCatId());
            st.setCatName(category.getCatName());
        });
        //  封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    // 添加学生
    @Override
    public boolean add(Product product) {
        return this.save(product);
    }
}
